package whu.cn.whushare.common;

import android.content.Context;
import android.widget.ImageView;

import com.android.volley.RequestQueue;
import com.android.volley.plus.ImageCache;
import com.android.volley.plus.TransitionImageListener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import whu.cn.whushare.util.FileManager;
import whu.cn.whushare.R;

public class ImageWorkerManager {
	private static ImageWorkerManager instance;
	private static ImageCache imageCache;
	private RequestQueue mQueue;
	private ImageLoader mImageLoader;

	private ImageWorkerManager(Context context) {
		init(context);
	}

	public synchronized static ImageWorkerManager getInstance(Context context) {
		if (instance == null) {
			instance = new ImageWorkerManager(context);
		}
		return instance;
	}

	/**
	 * 初始化全局图片缓存
	 *
	 * @param context
	 */
	private void init(Context context) {
		mQueue = Volley.newRequestQueue(context);
		ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(context,
				FileManager.CACHE_IMAGE_PATH_NEW);
		cacheParams.setMemCacheSizePercent(context, 0.2f);
		imageCache = new ImageCache(cacheParams);
		mImageLoader = new ImageLoader(mQueue, imageCache);
	}

	public ImageCache getImageCache() {
		return imageCache;
	}

	public ImageLoader getImageLoader() {
		return mImageLoader;
	}

    //清除图片缓存
	public void release() {
		if (imageCache != null) {
			imageCache.flush();
			imageCache.close();
		}
	}

	public void loadCommonImage(String coverUrl, ImageView imageView) {
		loadCommonImage(coverUrl, imageView, R.drawable.transparent, R.drawable.transparent, imageView.getWidth(),
				imageView.getHeight());
	}

	public void loadCommonImage(String coverUrl, ImageView imageView, int loadingDrawableId, int defaultDrawableId) {
		loadCommonImage(coverUrl, imageView, loadingDrawableId, defaultDrawableId, imageView.getWidth(),
				imageView.getHeight());
	}

	public void loadCommonImage(String coverUrl, ImageView imageView, int loadingDrawableId, int defaultDrawableId,
			int width, int height) {
		if (coverUrl == null) {
			coverUrl = "";
		}

		com.android.volley.plus.ImageCache cache = getImageCache();
		if (cache.getBitmapFromMemCache(coverUrl) != null) {
			imageView.setImageBitmap(cache.getBitmapFromMemCache(coverUrl));
		} else {
			ImageLoader.ImageContainer container = getImageLoader().get(coverUrl,
					TransitionImageListener.obtain(imageView, loadingDrawableId, defaultDrawableId), width, height);
			imageView.setTag(container);
		}
	}

	public void cancelRequest(ImageView imageView) {
		ImageLoader.ImageContainer container = (ImageLoader.ImageContainer) imageView.getTag();
		if (container != null) {
			container.cancelRequest();
			container.deleteListener();
		}

		imageView.setImageBitmap(null);
	}
}
